package com.ruoyi.framework.web;


import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * sys 用户工具类
 */
@Component
public class SysUserUtil {

    /**
     * 令牌服务
     */
    @Resource
    private TokenService tokenService;

    /**
     * 用户映射器
     */
    @Resource
    private SysUserMapper userMapper;
    /**
     * 声明对象
     */
    public static SysUserUtil userUtil;


    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        userUtil = this;
        userUtil.tokenService = this.tokenService;
        userUtil.userMapper = this.userMapper;
    }

    /**
     * 获取用户信息
     *
     * @return {@link SysUser }
     */
    public static SysUser getUserInfo() {
        LoginUser loginUser = userUtil.tokenService.getLoginUser(ServletUtils.getRequest());
        return loginUser == null ? null : loginUser.getUser();
    }

    /**
     * 获取用户 ID
     *
     * @return {@link String }
     */
    public static String getUserId() {
        SysUser sysUser = getUserInfo();
        if (sysUser != null) {
            return String.valueOf(sysUser.getUserId());
        }
        return null;
    }

    /**
     * 获取用户 ID str
     *
     * @return {@link String }
     */
    public static String getUserIdStr(){
        SysUser sysUser = getUserInfo();
        String userIdStr = "";
        if (Objects.nonNull(sysUser)) {
            userIdStr = Objects.toString(sysUser.getUserId(), "");
        }
        return userIdStr;
    }

    /**
     * 获取 dept id str
     *
     * @return {@link String }
     */
    public static String getDeptIdStr(){
        SysUser sysUser = getUserInfo();
        String deptIdStr = "";
        if (Objects.nonNull(sysUser)) {
            deptIdStr = Objects.toString(sysUser.getDeptId(), "");
        }
        return deptIdStr;
    }


    /**
     * 获取用户名
     *
     * @return {@link String }
     */
    public static String getUserName() {
        SysUser sysUser = getUserInfo();
        if (sysUser != null) {
            return sysUser.getUserName();
        }
        return null;
    }

}
